package com.testcase.settings;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.KeyEvent;

import com.testcase.R;
import com.testcase.splash.SplashScreen;

public class Settings extends PreferenceActivity {
	
	private static final int DIALOG_FAIL = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//This sets the PreferenceActivity which is different from setContentView for Activities
		addPreferencesFromResource(R.layout.settingslayout);
		
		//Set the background of the settings page
		getListView().setBackgroundDrawable(getResources().getDrawable(R.drawable.darkwoodwall));
	}
	
	//Override the back button when pressed to check if the information entered was correct
	//If it is incorrect prompt the user to change the credentials to ones that are correct
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
	    	Resources reso = getResources();
			String username = pref.getString(reso.getString(R.string.stsUsernameKey), null);
	    	String password = pref.getString(reso.getString(R.string.stsPasswordKey), null);
			if(!SplashScreen.isAuth(username, password)) {
				showDialog(DIALOG_FAIL);
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	//Dialog to show if the information changed is incorrect
	@Override
    protected Dialog onCreateDialog(int id) {
		switch (id) {
        case DIALOG_FAIL:
        	return new AlertDialog.Builder(Settings.this)
            .setTitle(R.string.faillogin)
            .setMessage(R.string.incorrect)
            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dismissDialog(DIALOG_FAIL);
                }
            })
            .create();
		}
		return null;
	}
}
